﻿#region Copyright and License Notice
// Copyright (C)2010-2016 - Rob Levine and other contributors
// http://configgen.codeplex.com
// 
// This file is part of ConfigGen.
// 
// ConfigGen is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// ConfigGen is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License and 
// the GNU Lesser General Public License along with ConfigGen.  
// If not, see <http://www.gnu.org/licenses/>
#endregion

using System;
using System.IO;
using ConfigGen.Core.ConfigurationSettings;
using ConfigGen.Core.TemplateLoader;
using ConfigGen.Core.TemplateProcessing;
using ConfigGen.Core.TokenHandling;

namespace ConfigGen.Core
{
    /// <summary>
    /// Provides the steps necessary to generate a single configuration file.
    /// </summary>
    public class SingleFileGenerator : ISingleFileGenerator
    {
        private readonly ITokenReplacer _tokenReplacer;
        private readonly ITokenLocator _tokenLocator;
        private MachineConfigurationSettings _currentMachine;
        private TokenCounts _tokenCounts;
        private TemplatePreferences _templatePreferences;

        /// <summary>
        /// Initializes a new instance of the <see cref="SingleFileGenerator"/> class.
        /// </summary>
        /// <param name="tokenReplacer">The token replacer.</param>
        /// <param name="tokenLocator">The token locator.</param>
        /// <exception cref="ArgumentNullException">Thrown if either argument is null.</exception>
        public SingleFileGenerator(ITokenLocator tokenLocator, ITokenReplacer tokenReplacer)
        {
            if (tokenReplacer == null) throw new ArgumentNullException("tokenReplacer");
            if (tokenLocator == null) throw new ArgumentNullException("tokenLocator");
            _tokenReplacer = tokenReplacer;
            _tokenLocator = tokenLocator;
        }
        
        /// <summary>
        /// Initialises the current instance using the arguments provided.
        /// </summary>
        /// <param name="currentMachine">Settings for the curent machine configuration being generated.</param>
        /// <param name="tokenCounts">Token count collections, containing counts of unused and unrecognised tokens.</param>
        /// <param name="templatePreferences">Template preferences.</param>
        /// <exception cref="ArgumentNullException">Thrown if any of the supplied arguments are null.</exception>
        public void Initialise(
            MachineConfigurationSettings currentMachine, 
            TokenCounts tokenCounts,
            TemplatePreferences templatePreferences)
        {
            if (currentMachine == null) throw new ArgumentNullException("currentMachine");
            if (tokenCounts == null) throw new ArgumentNullException("tokenCounts");
            if (templatePreferences == null) throw new ArgumentNullException("templatePreferences");

            _currentMachine = currentMachine;
            _tokenCounts = tokenCounts;
            _templatePreferences = templatePreferences;
        }

        /// <summary>
        /// Processes the supplied template source stream using the supplied template processor and writes the output onto
        /// the supplied processed template stream. This process is responsible for processing any custom configgen elements and
        /// attributes such as the applyWhen attribute. 
        /// </summary>
        /// <param name="sourceUnprocessedTemplateStream">Stream containing the unprocessed template source.</param>
        /// <param name="templateProcessor">Template processor.</param>
        /// <param name="targetProcessedTemplateStream">Stream onto which the target template is written.</param>
        /// <exception cref="ArgumentNullException">Thrown if any of the supplied arguments are null.</exception>
        public void ProcessTemplate(
            Stream sourceUnprocessedTemplateStream,
            ITemplateProcessor templateProcessor, 
            Stream targetProcessedTemplateStream)
        {
            if (sourceUnprocessedTemplateStream == null) throw new ArgumentNullException("sourceUnprocessedTemplateStream");
            if (templateProcessor == null) throw new ArgumentNullException("templateProcessor");
            if (targetProcessedTemplateStream == null) throw new ArgumentNullException("targetProcessedTemplateStream");

            try
            {
                templateProcessor.TokenUsed += _tokenCounts.IncrementTokenUseCount;
                templateProcessor.UnrecognisedToken += _tokenCounts.IncrementUnrecognisedTokenCount;
                templateProcessor.ProcessTemplate(sourceUnprocessedTemplateStream, targetProcessedTemplateStream, _currentMachine);
                targetProcessedTemplateStream.Position = 0;
            }
            finally
            {
                templateProcessor.TokenUsed -= _tokenCounts.IncrementTokenUseCount;
                templateProcessor.UnrecognisedToken -= _tokenCounts.IncrementUnrecognisedTokenCount;
            }
        }

        /// <summary>
        /// Replaces the tokens in the template with the tokens from the settings collection for the machine config being generated.
        /// </summary>
        /// <param name="sourceProcessedTemplateStream">Source processed template stream, being the processed template stream
        /// generated by <see cref="ProcessTemplate"/>.</param>
        /// <param name="targetConfigStream">The target stream on which to write the generated config file.</param>
        /// <exception cref="ArgumentNullException">Thrown if any of the supplied arguments are null.</exception>
        public void ReplaceTokens(
            Stream sourceProcessedTemplateStream,
            Stream targetConfigStream)
        {
            if (sourceProcessedTemplateStream == null) throw new ArgumentNullException("sourceProcessedTemplateStream");
            if (targetConfigStream == null) throw new ArgumentNullException("targetConfigStream");

            var generatedFile = new StreamWriter(targetConfigStream);
            
            using (var templateReader = new StreamReader(sourceProcessedTemplateStream))
            {
                _tokenReplacer.Initialise(_currentMachine);

                try
                {
                    _tokenLocator.TokenUsed += _tokenCounts.IncrementTokenUseCount;
                    _tokenLocator.UnrecognisedToken += _tokenCounts.IncrementUnrecognisedTokenCount;
                    _tokenLocator.LocateTokens(
                        templateReader,
                        generatedFile,
                        _templatePreferences.Token.StartDelimiter,
                        _templatePreferences.Token.EndDelimiter,
                        _tokenReplacer.GetTokenValue);
                }
                finally
                {
                    _tokenLocator.TokenUsed -= _tokenCounts.IncrementTokenUseCount;
                    _tokenLocator.UnrecognisedToken -= _tokenCounts.IncrementUnrecognisedTokenCount;
                }
            }

            generatedFile.Flush();
            targetConfigStream.Position = 0;
        }
    }
}
